import { getToken, removeToken, setToken } from "@/utils/token"
import { resetRouter } from "@/router"
import { getInfo, login, logout } from "@/api/UserApi"

const user = {
  state: {
    token: getToken(),
    avatar: "favicon.ico",
    nickname: "",
    username: "",
    phone: "",
    email: "",
    roles: [],
    permissions: []
  },

  mutations: {
    RESET_STATE: state => {
      state.token = getToken()
      state.avatar = "favicon.ico"
      state.nickname = ""
      state.username = ""
      state.phone = ""
      state.email = ""
      state.roles = []
      state.permissions = []
    },
    SET_USER: (state, user) => {
      state.avatar = user.avatar || "favicon.ico"
      state.nickname = user.nickname
      state.username = user.username
      state.phone = user.phone
      state.email = user.email
      state.roles = user.roles
      state.permissions = user.permissions
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar || "favicon.ico"
    }
  },

  actions: {
    // user login
    login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then(result => {
            let tokenValue = result.data[0].tokenValue
            commit("SET_TOKEN", tokenValue)
            setToken(tokenValue)
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // get user info
    current({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then(result => {
            const vo = result.data[0]
            if (!vo.permissions || vo.permissions.length === 0) vo.permissions = ["guest"]
            commit("SET_USER", vo)
            resolve(vo)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // user logout
    logout({ commit, dispatch }) {
      return new Promise((resolve, reject) => {
        logout()
          .then(() => {
            commit("SET_TOKEN", "")
            commit("SET_ROLES", [])
            commit("SET_PERMS", [])
            removeToken() // must remove  token  first
            resetRouter()
            dispatch("delAllViews", null, { root: true })
            commit("RESET_STATE")
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // remove token
    resetToken({ commit }) {
      return new Promise(resolve => {
        removeToken() // must remove  token  first
        commit("RESET_STATE")
        resolve()
      })
    }
  }
}
export default user
